package com.zhou.imaotai.service.web;


import cn.hutool.core.date.DateUtil;
import com.zhou.imaotai.core.RedisCache;
import com.zhou.imaotai.model.LoginUser;
import com.zhou.imaotai.entity.SysUserEntity;
import com.zhou.imaotai.exception.ServiceException;
import com.zhou.imaotai.security.context.AuthenticationContextHolder;
import com.zhou.imaotai.service.SysUserService;
import com.zhou.imaotai.utils.ServletUtils;
import com.zhou.imaotai.utils.StringUtils;
import com.zhou.imaotai.utils.ip.IpUtils;
import com.zhou.imaotai.utils.web.WebFrameworkUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author lcz
 * @desc 登录校验方法
 * @mail lcz_0130@163.com
 * @date 2024/03/26
 */
@Component
public class SysLoginService {
    private static final Logger logger = LoggerFactory.getLogger(SysLoginService.class);

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserService userService;

    // 验证码开关
    @Value("${token.captchaEnabled}")
    private Boolean captchaEnabled;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 验证码开关
        if (captchaEnabled) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                //异步执行->保存登录信息
                throw new ServiceException("账号或密码错误");
            } else {
                //异步执行->登录信息
                e.printStackTrace();
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //异步记录登录成功日志
        // 额外设置到 request 中，有的过滤器在 Spring Security 之前
        WebFrameworkUtils.setLoginUserId(ServletUtils.getRequest(), loginUser.getUserId());
        //记录登录信息
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = "captcha_codes:" + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            logger.error("验证码失效：code:" + code + ",captcha:" + captcha);
            throw new ServiceException("验证码失效");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            logger.error("验证码错误：code:" + code + ",captcha:" + captcha);
            throw new ServiceException("验证码错误");
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUserEntity sysUser = new SysUserEntity();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtil.date());
        userService.updateUserProfile(sysUser);
    }
}
